package org.product.controller.message;

import com.google.gson.Gson;
import org.product.controller.BaseServlet;
import org.product.dao.MessageDao;
import org.product.dao.ReplayDao;
import org.product.dao.UserDao;
import org.product.dao.impl.MessageDaoImpl;
import org.product.dao.impl.ReplayDaoImpl;
import org.product.entity.Message;
import org.product.entity.Replay;
import org.product.entity.User;
import org.product.factory.DaoFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 用户登录
 */
@WebServlet("/api/queryAllMessage.do")
public class QueryAllMessageServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {



        // 第一：创建DAO对象，实现数据添加操作
        MessageDao messageDao = new MessageDaoImpl() ;
        ReplayDao replayDao = new ReplayDaoImpl() ;

        // 第二：查询数据
        List<Message> messageList = messageDao.queryAllMessage() ;

        // 第三：组装数据
        for(Message m : messageList) {
            // 根据留言的ID，查询对应的所有回复
            List<Replay> replayList = replayDao.queryAllReplay(m.getId()) ;

            m.setReplayList(replayList);
        }


        // 第四：响应结果
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter() ;


        out.print(new Gson().toJson(successJson(messageList)));
//        [{
//            title:xx ,
//            content:xx ,
//            ...
//            replayList:[{
//                title:yy,
//                content:yy
//            }
//            }
//            ]
//
//        },{}]


        // 第五：关闭对象
        out.flush();
        out.close();
    }
}
